package com.iis.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.iis.databaseutil.DatabaseConnection;
import com.iis.entity.Person;

public class PersonDAO {

	private static final PersonDAO personDAO = new PersonDAO();

	private PersonDAO() {

	}

	public static PersonDAO getInstance() {
		return personDAO;
	}

	Connection koneksiKu = null;

	PreparedStatement psInsertPerson = null;

	String sqlInsertPerson = "INSERT INTO Person(name, address) "
			+ "VALUES (?,?) ";

	public Person save(Person newPerson) throws SQLException {
		if (newPerson == null) {
			return null;
		}
		koneksiKu = DatabaseConnection.getDataConnection(false);
		int index = 1;
		try {

			psInsertPerson = koneksiKu.prepareStatement(sqlInsertPerson,
					Statement.RETURN_GENERATED_KEYS);
			psInsertPerson.setString(index++, newPerson.getName());
			psInsertPerson.setString(index++, newPerson.getAddress());
			int jumlahRow = psInsertPerson.executeUpdate();
			if (jumlahRow == 0) {
				throw new SQLException("Gagal menyimpan person");
			}
			try (ResultSet generatedKeys = psInsertPerson.getGeneratedKeys()) {
				if (generatedKeys.next()) {
					newPerson.setPersonID(generatedKeys.getLong(1));
					return newPerson;
				} else {
					throw new SQLException("Gagal menyimpan person");
				}
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

}
